/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package handlers;

import java.io.IOException;
import java.util.LinkedList;
import javax.servlet.*;
import javax.servlet.http.*;
import readers.UserReader;
import writers.UserWriter;

/**
 *
 * @author Chris
 */
public class addGroupHandler extends HttpServlet {
    static void failAdd(HttpServletRequest request, HttpServletResponse response)
    throws IOException {
        response.sendRedirect("groups.jsp");
    }
    
    protected void process(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String user = getUserName(request, response);
        String grpId = request.getParameter("grpid");
        if(grpId == null || user == null) {
            failAdd(request, response);
            return;
        }
        
        LinkedList<String> lst = new LinkedList<String>();
        
        UserReader.getTeacherGroups(user, lst); //Doesn't matter if it failed
        
        if(lst.contains(grpId)) {
            failAdd(request, response); //Already exists do nothing
            return;
        }
        
        lst.add(grpId);
        UserWriter.setTeacherGroups(user, lst);
        response.sendRedirect("groups.jsp");
        return;
    }
                
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        process(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        process(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Handles login information";
    }
    
    private static String getUserName(HttpServletRequest request, HttpServletResponse response) {
        try {
            int i;
            Cookie[] cookies = request.getCookies();
            Cookie cookieUN = null;
            if(cookies.length == 0) {
                failAdd(request, response);
            }
            
            for(i=0; i<cookies.length; i++) {
                if(cookies[i].getName().equals("username"))
                    return cookies[i].getValue();
            }
            
            if(cookieUN == null) {
                failAdd(request, response);
            }
            return null;
        }
        catch(Exception ex) {
        }
        return null;
    }
}
